package com.dapeis.api.spring.interceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.ag.core.exception.NoLoginException;
import com.dapeis.api.controller.RestController;
import com.dapeis.api.utils.ApiTokenUtils;
import com.dapeis.api.utils.threadlocal.UserThreadLocal;
import com.dapeis.domain.User;
import com.dapeis.service.UserService;

/**
 * 用户端需要登录拦截入口
 * Title:StylistUserAuthApiInterceptor.java StylistUserAuthApiInterceptor
 * Description:
 * @author yuanyong
 * @date 2017年4月20日 下午4:30:09 
 * Email: hzyuanyong@126.com
 *
 */
public class StylistUserAuthApiInterceptor implements HandlerInterceptor {
	final Logger logger = LoggerFactory.getLogger(getClass());
	public static UserThreadLocal userThreadLocal = new UserThreadLocal();
	@Resource UserService userService;
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		Integer userId = ApiTokenUtils.tokenCheckAndGet(request, ApiTokenUtils.USER_REDIS_PRE_KEY);
		userThreadLocal.resetUserId(userId);
		
		User user = RestController.getThreadLocalUser();
		if(user == null) {
			throw new NoLoginException();
		}
		
		userService.checkUserVaild(user);
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
	}

	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		userThreadLocal.remove();
	}

}
